package com.example.cemenghuii.controller;

import com.example.cemenghuii.dto.ApiResponse;
import com.example.cemenghuii.dto.LoginRequest;
import com.example.cemenghuii.dto.RegisterRequest;
import com.example.cemenghuii.entity.User;
import com.example.cemenghuii.service.UserService;
import com.example.cemenghuii.util.JwtUtil;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "*")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ApiResponse<Map<String, Object>> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            User user = userService.login(loginRequest.getUsername(), loginRequest.getPassword());
            if (user == null) {
                return ApiResponse.error("用户名或密码错误");
            }

            // 生成JWT token
            String token = jwtUtil.generateToken(user.getId(), user.getUsername(), user.getUserType());

            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("user", user);

            return ApiResponse.success("登录成功", result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ApiResponse<Void> register(@Valid @RequestBody RegisterRequest registerRequest) {
        try {
            // 验证两次密码是否一致
            if (!registerRequest.getPassword().equals(registerRequest.getConfirmPassword())) {
                return ApiResponse.badRequest("两次输入的密码不一致");
            }

            User user = new User();
            user.setCompanyName(registerRequest.getCompanyName());
            user.setUsername(registerRequest.getUsername());
            user.setPassword(registerRequest.getPassword());
            user.setContactInfo(registerRequest.getContactInfo());
            user.setPhone(registerRequest.getPhone());
            user.setEmail(registerRequest.getEmail());

            boolean success = userService.register(user);
            if (success) {
                return ApiResponse.success("注册成功");
            } else {
                return ApiResponse.error("注册失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/info")
    public ApiResponse<User> getUserInfo(@RequestHeader("Authorization") String token) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);

            User user = userService.getUserById(userId);
            if (user == null) {
                return ApiResponse.notFound("用户不存在");
            }

            return ApiResponse.success(user);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/info")
    public ApiResponse<Void> updateUserInfo(@RequestHeader("Authorization") String token,
                                            @RequestBody User user) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);

            user.setId(userId);
            // 不允许通过此接口修改密码和用户类型
            user.setPassword(null);
            user.setUserType(null);

            boolean success = userService.updateUser(user);
            if (success) {
                return ApiResponse.success("更新成功");
            } else {
                return ApiResponse.error("更新失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 修改密码
     */
    @PutMapping("/password")
    public ApiResponse<Void> updatePassword(@RequestHeader("Authorization") String token,
                                            @RequestBody Map<String, String> passwordData) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);

            String oldPassword = passwordData.get("oldPassword");
            String newPassword = passwordData.get("newPassword");
            String confirmPassword = passwordData.get("confirmPassword");

            if (!newPassword.equals(confirmPassword)) {
                return ApiResponse.badRequest("两次输入的新密码不一致");
            }

            boolean success = userService.updatePassword(userId, oldPassword, newPassword);
            if (success) {
                return ApiResponse.success("密码修改成功");
            } else {
                return ApiResponse.error("密码修改失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取用户列表（管理员功能）
     */
    @GetMapping("/list")
    public ApiResponse<Map<String, Object>> getUserList(@RequestHeader("Authorization") String token,
                                                        @RequestParam(required = false) String username,
                                                        @RequestParam(required = false) String phone,
                                                        @RequestParam(required = false) Integer status,
                                                        @RequestParam(defaultValue = "1") Integer page,
                                                        @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);

            // 检查是否为超级管理员
            if (!userService.isSuperAdmin(userId)) {
                return ApiResponse.forbidden("权限不足");
            }

            Map<String, Object> result = userService.getUserList(username, phone, status, page, pageSize);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 创建用户（管理员功能）
     */
    @PostMapping("/create")
    public ApiResponse<Void> createUser(@RequestHeader("Authorization") String token,
                                        @RequestBody User user) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);

            // 检查是否为超级管理员
            if (!userService.isSuperAdmin(userId)) {
                return ApiResponse.forbidden("权限不足");
            }

            boolean success = userService.createUser(user);
            if (success) {
                return ApiResponse.success("用户创建成功");
            } else {
                return ApiResponse.error("用户创建失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 更新用户状态（管理员功能）
     */
    @PutMapping("/{id}/status")
    public ApiResponse<Void> updateUserStatus(@RequestHeader("Authorization") String token,
                                              @PathVariable Long id,
                                              @RequestBody Map<String, Integer> statusData) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);

            // 检查是否为超级管理员
            if (!userService.isSuperAdmin(userId)) {
                return ApiResponse.forbidden("权限不足");
            }

            Integer status = statusData.get("status");
            boolean success = userService.updateUserStatus(id, status);
            if (success) {
                return ApiResponse.success("状态更新成功");
            } else {
                return ApiResponse.error("状态更新失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 删除用户（管理员功能）
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteUser(@RequestHeader("Authorization") String token,
                                        @PathVariable Long id) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);

            // 检查是否为超级管理员
            if (!userService.isSuperAdmin(userId)) {
                return ApiResponse.forbidden("权限不足");
            }

            // 不能删除自己
            if (userId.equals(id)) {
                return ApiResponse.badRequest("不能删除自己");
            }

            boolean success = userService.deleteUser(id);
            if (success) {
                return ApiResponse.success("用户删除成功");
            } else {
                return ApiResponse.error("用户删除失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 重置用户密码（管理员功能）
     */
    @PutMapping("/{id}/reset-password")
    public ApiResponse<Void> resetPassword(@RequestHeader("Authorization") String token,
                                           @PathVariable Long id,
                                           @RequestBody Map<String, String> passwordData) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);

            // 检查是否为超级管理员
            if (!userService.isSuperAdmin(userId)) {
                return ApiResponse.forbidden("权限不足");
            }

            String newPassword = passwordData.get("newPassword");
            boolean success = userService.resetPassword(id, newPassword);
            if (success) {
                return ApiResponse.success("密码重置成功");
            } else {
                return ApiResponse.error("密码重置失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 验证token
     */
    @GetMapping("/validate-token")
    public ApiResponse<Map<String, Object>> validateToken(@RequestHeader("Authorization") String token) {
        try {
            String jwt = token.replace("Bearer ", "");

            if (jwtUtil.validateToken(jwt)) {
                Long userId = jwtUtil.getUserIdFromToken(jwt);
                String username = jwtUtil.getUsernameFromToken(jwt);
                Integer userType = jwtUtil.getUserTypeFromToken(jwt);

                Map<String, Object> result = new HashMap<>();
                result.put("valid", true);
                result.put("userId", userId);
                result.put("username", username);
                result.put("userType", userType);

                return ApiResponse.success(result);
            } else {
                return ApiResponse.unauthorized("Token无效");
            }
        } catch (Exception e) {
            return ApiResponse.unauthorized("Token验证失败");
        }
    }
}